#ifndef __EVENTLOOP_HPP__
#define __EVENTLOOP_HPP__

#include "TcpConnection.hpp"
#include <sys/epoll.h>
#include <memory>
#include <vector>
#include <map>
#include <functional>
#include <mutex>

namespace wd
{
class TcpConnection; 
class Acceptor;

using std::shared_ptr;
using std::vector;
using std::map;
using std::function;
using std::mutex;

using TcpConnectionPtr =shared_ptr<TcpConnection>;
using CallBack = function<void(TcpConnectionPtr)>;
using Functor = function<void()>;

class EventLoop
{
public:
    EventLoop(Acceptor &);
    ~EventLoop();

    void loop();
    void closeLoop();
    void functorToLoop(Functor&&);
    void doPendingFunctor();

    void setCallBack(const CallBack &,const CallBack&,const CallBack&);
private:
    int creatEpollFd();
    int creatEventFd();
    void waitEpollFd();
    void wakeup();

    void addEpollEvent(int);
    void delEpollEvent(int);

    void handleNewConnection();
    void handleMessage(int);
    void handleReadEvent();

private:
    int _epfd;
    Acceptor & _accept;
    int _eventfd;
    vector<struct epoll_event> _evsArr; 
    map<int,TcpConnectionPtr> _connPtr;
    vector<Functor> _functor;

    bool _isLooping;
    mutex _mutex;

    CallBack _onConnection;
    CallBack _onMessage;
    CallBack _onClosed;
};

}//end of namespace



#endif // __EVENTLOOP_HPP__

